﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace Acme.BookStore2.EntityFrameworkCore
{
    public class VehicleMaintenanceRecordRepository : EfCoreRepository<BookStore2DbContext, VehicleMaintenanceRecord, Guid>,
        IVehicleMaintenanceRecordRepository
    {
        public VehicleMaintenanceRecordRepository(IDbContextProvider<BookStore2DbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<List<VehicleMaintenanceRecord>> GetPagedListAsync(
            int skipCount, 
            int maxResultCount, 
            string sorting, 
            Guid? vehicleId = null,          
            DateTime? startDateBegin = null,
            DateTime? startDateEnd = null,
            bool includeDetails = false, 
            CancellationToken cancellationToken = default)
        {
            return await DbSet
                .WhereIf(vehicleId.HasValue, v => v.VehicleId == vehicleId)
                .WhereIf(startDateBegin.HasValue, v => v.StartDate >= startDateBegin)
                .WhereIf(startDateEnd.HasValue, v => v.StartDate <= startDateEnd)
                .OrderBy(sorting ?? nameof(VehicleMaintenanceRecord.CreationTime) + " desc")
                .PageBy(skipCount, maxResultCount)
                .ToListAsync(GetCancellationToken(cancellationToken));
        }

        public async Task<long> GetCountAsync(
            Guid? vehicleId = null,
            DateTime? startDateBegin = null,
            DateTime? startDateEnd = null,
            CancellationToken cancellationToken = default)
        {
            return await this
                .WhereIf(vehicleId.HasValue, v => v.VehicleId == vehicleId)
                .WhereIf(startDateBegin.HasValue, v => v.StartDate >= startDateBegin)
                .WhereIf(startDateEnd.HasValue, v => v.StartDate <= startDateEnd)
                .LongCountAsync(GetCancellationToken(cancellationToken));
        }
    }
}